<script setup lang="ts">
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat, toYuan, getNowDay } from '@/hooks/util'
import * as accountApi from '@/api/account'

import { message } from 'ant-design-vue'

const route = useRoute()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
}
const pagination = ref<Pagination>({ page: 1, pageSize: 10, total: 0 })
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  orderNumber?: string
  changeType?: string
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '订单ID',
    key: 'orderId',
    width: 150,
  },
  {
    title: '变动金额',
    key: 'changeBalance',
    width: 150,
  },
  {
    title: '变动类型',
    key: 'changeType',
    width: 150,
  },
  {
    title: '变动前金额',
    key: 'beforeBalance',
    width: 150,
  },
  {
    title: '变动后金额',
    key: 'afterBalance',
    width: 150,
  },
  {
    title: '变动时间',
    key: 'updateTime',
    width: 150,
  },
  {
    title: '变动备注',
    key: 'changeRemark',
    width: 150,
  },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 90,
  //   fixed: 'right',
  // },
]
// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  // console.log('selectedRowKey=', selectedRowKeys)
  selectedRowKey.value = selectedRowKeys

  // console.log('selectedRow=', selectedRows)
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await accountApi.getUserBalanceRecordList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

// 	变动类型
import type { SelectProps } from 'ant-design-vue'
const typeList = ref<SelectProps['options']>([
  {
    label: '充值',
    value: '1',
  },
  // {
  //   label: '扣款',
  //   value: '2',
  // },
  {
    label: '订单解冻',
    value: '3',
  },
  {
    label: '后台操作加款',
    value: '4',
  },
  {
    label: '订单退款',
    value: '5',
  },
  {
    label: '订单扣款',
    value: '11',
  },
  {
    label: '订单冻结',
    value: '12',
  },
  {
    label: '后台操作扣款',
    value: '14',
  },
])

const compileType = (type: number | string) =>
  typeList.value?.find(item => item.value == type)?.label

onMounted(() => getList())

// 查询
const formRef = ref()
interface FormState {
  changeType?: string
  orderNumber?: string
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    // console.log('formState=', formState)
    searchParams.value.orderNumber = formState.orderNumber || ''
    searchParams.value.changeType = formState.changeType || ''
    // console.log('searchParams=', searchParams.value)
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'orderNumber')
  Reflect.deleteProperty(searchParams.value, 'changeType')

  getList()
}

// 导出表格
let exportExcelLoading = ref<boolean>(false)
const exportExcel = async () => {
  try {
    exportExcelLoading.value = true
    let { state, data, message: msg } = await accountApi.userBalanceRecordExcelOut(searchParams.value)
    // console.log('data=', data)
    let blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    let file = new File([blob], `资金明细-${getNowDay()}.xlsx`, {
      lastModified: new Date() as any,
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    // console.log('file=', file)
    const a = document.createElement('a')
    a.style.display = 'none'
    document.body.appendChild(a)
    const url = URL.createObjectURL(file)
    a.href = url
    a.download = file.name
    a.click()
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  exportExcelLoading.value = false
}
</script>

<template>
  <page-container :title="route.meta.title">
    <a-card style="overflow-x: scroll">
      <div class="searchBox">
        <a-form ref="formRef" layout="inline" :model="formState">
          <a-form-item label="订单编号" name="orderNumber">
            <a-input v-model:value="formState.orderNumber" placeholder="订单编号" />
          </a-form-item>

          <a-form-item label="变动类型" name="changeType">
            <a-select
              v-model:value="formState.changeType"
              placeholder="请选择"
              style="width: 150px"
            >
              <a-select-option v-for="(item, index) in typeList" :key="index" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <a-button type="primary" @click="search">
          <template #icon><SearchOutlined /></template>
          搜索
        </a-button>
        <a-button @click="reset">重置</a-button>
        <a-button :loading="exportExcelLoading" @click="exportExcel" :disabled="true">导出近七天</a-button>
      </div>

      <a-table
        style="overflow-x: scroll"
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        :loading="loading"
        @change="changePage"
        rowKey="id"
      >
        <!-- :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }" -->
        <template #emptyText>
          <a-empty description="暂无数据" />
        </template>

        <template #headerCell="{ column }">
          <template v-if="column.key === 'id'">
            <span>id</span>
          </template>
          <template v-else-if="column.key === 'orderId'">
            <div>订单编号</div>
          </template>
          <template v-else-if="column.key === 'changeType'">
            <div>变动类型</div>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'orderId'">
            <div style="width: 150px">{{ record.orderNumber || '无' }}</div>
          </template>

          <template v-if="column.key === 'robotId'">
            <div style="width: 150px">{{ record.robotId }}</div>
          </template>

          <template v-else-if="column.key === 'changeBalance'">
            <div style="width: 150px">
              <a>￥{{ toYuan(record.changeBalance) }}</a>
            </div>
          </template>

          <template v-else-if="column.key === 'changeType'">
            <a-tag
              color="red"
              v-if="
                record.changeType == '2' || record.changeType == '11' || record.changeType == '12'
              "
            >
              {{ compileType(record.changeType) }}
            </a-tag>
            <a-tag color="blue" v-else>{{ compileType(record.changeType) }}</a-tag>
          </template>

          <template v-if="column.key === 'changeRemark'">
            <a-popover>
              <template #content>
                <div style="width: 400px; overflow-x: scroll">
                  {{ record.changeRemark }}
                </div>
              </template>
              <div class="hiddenText">{{ record.changeRemark }}</div>
            </a-popover>
          </template>

          <template v-else-if="column.key === 'beforeBalance'">
            <div style="width: 150px">
              <a>￥{{ toYuan(record.beforeBalance) }}</a>
            </div>
          </template>

          <template v-else-if="column.key === 'afterBalance'">
            <div style="width: 150px">
              <a>￥{{ toYuan(record.afterBalance) }}</a>
            </div>
          </template>

          <template v-else-if="column.key === 'updateTime'">
            <div style="width: 160px">{{ timeFormat(record.updateTime) }}</div>
          </template>

          <template v-else-if="column.key === 'action'"></template>
        </template>
      </a-table>
    </a-card>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
